﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace HJ_SQL_ToTable
{
    /// <summary>
    ///     SQL语句提取工具
    /// </summary>
    public class SQLExtractor
    {

        public static List<SQLTable> Extract(List<string> sqls, ref string msg)
        {
            List<SQLTable> tables = new List<SQLTable>();
            SQLTable table;

            try
            {
                foreach (var sql in sqls)
                {
                    if ((table = Extract(sql, ref msg)) != null)
                        tables.Add(table);
                }
            }
            catch (Exception ex)
            {
                tables.Clear();
            }

            return tables;
        }

        public static SQLTable Extract(string sql, ref string msg)
        {
            SQLTable table;
            var sqlFormated = sql.Replace("\r", "");
            var subs = sqlFormated.Split(new string[] { "\n" }, StringSplitOptions.RemoveEmptyEntries);

            if (subs.Length == 0)
                return null;

            table = Extract(subs, ref msg);

            return table;
        }

        public static SQLTable Extract(string[] lines, ref string msg)
        {
            SQLTable table = null;
            if (lines == null || lines.Length == 0)
                return null;

            ExtractSQLLineResult result;

            try
            {
                /*
                 CREATE TABLE `api_admin_apiaccessconfig` (
                      `id` int(11) NOT NULL AUTO_INCREMENT,
                      `change_date` datetime(6) NOT NULL,
                      `enabled` tinyint(1) NOT NULL,
                      `changed_by_id` int(11) DEFAULT NULL,
                      PRIMARY KEY (`id`),
                      KEY `api_admin_apiacce_changed_by_id_771a504ee92a076c_fk_auth_user_id` (`changed_by_id`),
                      CONSTRAINT `api_admin_apiacce_changed_by_id_771a504ee92a076c_fk_auth_user_id` FOREIGN KEY (`changed_by_id`) REFERENCES `auth_user` (`id`)
                    ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
                 */
                table = new SQLTable();
                table.Fields = new List<SQLField>();
                foreach (var line in lines)
                {
                    result = ExtractField(line, ref msg);
                    if (result == null)
                        break;

                    if (result.IsTableName)
                    {
                        table.TableName = result.Name;
                    }
                    else
                    {
                        if (result.IsField)
                        {
                            SQLField field = new SQLField
                            {
                                CanSetNull = result.CanSetNull,
                                FieldName = result.FieldName,
                                FieldLength = result.FieldLength,
                                FieldType = result.FieldType,
                                //IsPrimaryKey = result.IsPrimaryKey,
                            };

                            table.Fields.Add(field);
                        }
                        else
                        {
                            //设置某一个为主键
                            if (result.IsPrimaryKey){
                                foreach (var field_sub in table.Fields) {
                                    if (string.Compare(result.Key, field_sub.FieldName, true) == 0) {
                                        field_sub.IsPrimaryKey = true;
                                        break;
                                    }
                                }
                            }
                            else {
                                if (string.Compare(result.Key, "Engine", true) == 0){
                                    table.Engine = result.Name;
                                }

                                if (string.Compare(result.Key, "Charset", true) == 0){
                                    table.Charset = result.Name;
                                }
                            }
                        }

                    }
                }
            }
            catch (Exception ex) { table = null;
            }

            return table;
        }

        public static ExtractSQLLineResult ExtractField(string line, ref string msg)
        {
            ExtractSQLLineUtil eutil = new ExtractSQLLineUtil();
            if (eutil.Extract(line))
                return eutil.Results;
            else
            {
                msg = eutil.ErrMsg;
            }
            
            return null;
        }
    }
}
